package com.pengtu.web.project.labs;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;

import com.pengtu.dao.Page;
import com.pengtu.dao.QueryFilter;
import com.pengtu.entity.app.Department;
import com.pengtu.entity.app.User;
import com.pengtu.entity.app.UserDepartment;
import com.pengtu.service.app.AccountManager;
import com.pengtu.utils.encode.JsonBinder;
import com.pengtu.utils.web.Struts2Utils;
import com.pengtu.web.BaseActionSupport;

@Results({ @Result(name = BaseActionSupport.RELOAD, location = "${ctx}/project/labs/userdepartment.action?organizationId=${organizationId}&projectId=${projectId}&typeId=${typeId}&deptId=${deptId}", type = "redirect") })
public class UserdepartmentAction extends BaseActionSupport<UserDepartment> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private AccountManager accountManager;
	private UserDepartment entity;
	private User user;
	private String id;
	private List<UserDepartment> userDepartments;
	private Page<UserDepartment> page = new Page<UserDepartment>(10);// 每页5条记录
	private String deptId;
	private String projectId;
	private String typeId;
	private String organizationId;

	@Override
	public String list() throws Exception {
		// TODO Auto-generated method stub
		QueryFilter queryfilters = QueryFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		if("1".equals(typeId)){
			queryfilters.addFilter("department.organization.id", deptId);
		}else{
			queryfilters.addFilter("department.fid", deptId);
		}
		if (!page.isOrderBySetted()) {
			page.setOrderBy("id");
			page.setOrder(Page.DESC);
		}
		page = accountManager.searchUserDepartment(page, queryfilters);
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		// TODO Auto-generated method stub
		if(StringUtils.isNotEmpty(id))return "update" ;
		return INPUT;
	}

	@Override
	public String save() throws Exception {
		accountManager.saveUser(entity.getUser());
		accountManager.save(entity);
		addActionMessage("保存" + entity.getUser().getName() + "信息！");
		return "successMessage";
	}
	
	public void deleteUserDept(){
		accountManager.deleteUserDept(id);
		addActionMessage("删除Id为"+id+"的用户部门信息!");
		Struts2Utils.renderText("1");
	}
	
	@Override
	public String delete() throws Exception {
		// TODO Auto-generated method stub
		accountManager.deleteUserDept(id);
		addActionMessage("删除人员信息！");
		return RELOAD;
	}
	/**
	 * 
	 * checkEmail:
	 * 适用:验证邮箱是否重复注册
	 * @exception 
	 * @since  1.0.0
	 */
	public void checkEmail() {
		String email = Struts2Utils.getParameter("user.email");
		String oldEmail = Struts2Utils.getParameter("oldEmail");
		if (accountManager.isEmail(email, oldEmail)) {
			Struts2Utils.renderText("true");
		} else {
			Struts2Utils.renderText("false");
		}
	}

	@Override
	protected void prepareModel() throws Exception {
		// TODO Auto-generated method stub
		if (StringUtils.isEmpty(id)) {
			entity = new UserDepartment();
		} else {
			entity = accountManager.getUserDepartmentById(id);
		}
	}

	/**
	 * 
	 * userDetails:
	 * 适用:显示部门下的所有员工信息
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Action("/project/labs/ext/userdepartment")
	public String userDetails() {
		// TODO Auto-generated method stub
		return VIEW;
	}
	
	

	/**
	 * @throws JSONException
	 * 
	 */
	public String deptShow() throws Exception {
		// 获得当前部门下的所有子部门
		List<Department> userDeptList = accountManager.getChildrenDept(deptId);
		// 获得当前部门
		Department deptJson = accountManager.getDepartment(deptId);
		// 将数据按键值对的形式保存到Map集合中，转换为Json格式在页面显示
		Map<String, Object> fatherDept = new HashMap<String, Object>();
		fatherDept.put("id", deptJson.getId());
		fatherDept.put("qtip", deptJson.getDepAllName());
		fatherDept.put("text", deptJson.getDepName());

		// 将子部门保存到List集合中，实现页面的节点显示
		List<Map<String, Object>> childrenJson = new ArrayList<Map<String, Object>>();
		for (Department department : userDeptList) {
			Map<String, Object> childrenDept = new HashMap<String, Object>();
			childrenDept.put("id", department.getId());
			childrenDept.put("qtip", department.getDepAllName());
			childrenDept.put("text", department.getDepName());
			childrenDept.put("leaf", Boolean.TRUE);
			childrenJson.add(childrenDept);
		}
		// 将子部门集合保存到父节点中
		fatherDept.put("children", childrenJson);
		// 转换数据为Jkson格式
		Struts2Utils.renderJson("["
				+ JsonBinder.buildNonDefaultBinder().toJson(fatherDept) + "]");
		return NONE;
	}

	public String userDetail() {
		List<UserDepartment> userList = accountManager.findUserDept("department.id",deptId);
		List<Map<String, Object>> userDetailList = new ArrayList<Map<String, Object>>();
		for (UserDepartment userDept : userList) {
			Map<String, Object> user = new HashMap<String, Object>();
			user.put("id", userDept.getId());
			user.put("name", userDept.getUser().getName());
			user.put("dutyName", userDept.getUser().getDutyName());
			user.put("officalPosition", userDept.getOfficalPosition());
			user.put("startDate", userDept.getStartDate());
			user.put("endDate", userDept.getEndDate());
			userDetailList.add(user);
		}
		Struts2Utils.renderJsontoExtTotalResults(userDetailList);
		return NONE;
	}

	public String getDeptId() {
		return deptId;
	}

	public void setDeptId(String deptId) {
		this.deptId = deptId;
	}

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	public UserDepartment getEntity() {
		return entity;
	}

	public void setEntity(UserDepartment entity) {
		this.entity = entity;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public List<UserDepartment> getUserDepartments() {
		return userDepartments;
	}

	public void setUserDepartments(List<UserDepartment> userDepartments) {
		this.userDepartments = userDepartments;
	}

	public Page<UserDepartment> getPage() {
		return page;
	}

	public void setPage(Page<UserDepartment> page) {
		this.page = page;
	}

	@Override
	public UserDepartment getModel() {
		// TODO Auto-generated method stub
		return entity;
	}

	public String getProjectId() {
		return projectId;
	}

	public void setProjectId(String projectId) {
		this.projectId = projectId;
	}

	public String getTypeId() {
		return typeId;
	}

	public void setTypeId(String typeId) {
		this.typeId = typeId;
	}

	public String getOrganizationId() {
		return organizationId;
	}

	public void setOrganizationId(String organizationId) {
		this.organizationId = organizationId;
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
}
